package com.kungfuhacking.wristbandpro.mqtt;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.kungfuhacking.wristbandpro.utils.CommonUtils;
import com.kungfuhacking.wristbandpro.utils.Constant;

import mqttresource.IMqttDeliveryToken;
import mqttresource.MqttCallback;
import mqttresource.MqttMessage;


/**
 * mqtt消息回调
 * Created by Aaron on 15/12/15.
 */
public class MqttMessageCallBack implements MqttCallback {

    private Context ctx;
    private String TAG = getClass().getSimpleName();

    public MqttMessageCallBack(Context ctx) {
        this.ctx = ctx;
    }

    SharedPreferences sp;

    @Override
    public void connectionLost(Throwable throwable) {

        Log.e(TAG, " 连接中断 " + throwable.getMessage()
                + ", throwable:" + throwable.toString() + ",LocalizedMessage:" + throwable.getLocalizedMessage()
                + ", Cause :" + throwable.getCause().getMessage());

        throwable.printStackTrace();

        //网络不可用
        if (ctx == null || !CommonUtils.isNetworkConnected(ctx)) {
            return;
        }

        if (sp == null)
            sp = ctx.getSharedPreferences(Constant.CONFIG, Context.MODE_PRIVATE);

        if (sp.getBoolean(MqttConstant.INTERVAL_CONNET_MQTT, true))
            //获取mqtt聊天服务器ip和端口,重新连接
            MqttManager.getInstance().getMqttIp(ctx);

    }

    //    int i = 0;
    @Override
    public void messageArrived(String topic, MqttMessage message) {

        //此线程为子线程
        Log.e(TAG, "收到的消息:" + "topic:" + topic + ",消息内容:" + message.toString() +
                ", 是否是主线程 : " + (Looper.getMainLooper() == Looper.myLooper()));

        if (TextUtils.isEmpty(message.toString()))
            return;

        synchronized (this) {
//            i++;
//            Log.e("tag", " 开始处理 消息 : " + i);
            ChatMessageManager.getInstance().handlerMessage(topic, message.toString(), ctx);
//            Log.e("tag", " 消息处理完毕 : " + i);
        }

    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }


}